package com.zx.kitchen.index.common.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zx.kitchen.index.R;
import com.zx.kitchen.index.common.adapter.EditInfoAdapter;
import com.zx.kitchen.index.common.entity.DishesInfoBean;
import com.zx.kitchen.index.common.entity.DishesListBean;
import com.zx.kitchen.index.common.entity.EditInfoBean;
import com.zx.kitchen.index.common.entity.OrderCreateBean;
import com.zx.kitchen.index.common.http.HttpIndex;
import com.zx.kitchen.index.common.mvp.OnResultListener;
import com.zx.kitchen.index.common.utils.ArithmeticUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2017/3/5.
 */

public class EditInfoActivity extends Activity implements View.OnClickListener {
    private ImageView toolbarLeft;
    private TextView toolbarTitle;
    private ListView listOrderEdit;
    private TextView btnClearAll, btnAdd, btnCancle, btnConfirm;
    private EditInfoAdapter adapter;
    private List<DishesInfoBean> mList = new ArrayList<>();
    private Spinner selectCustomSpinner;
    private static String[] mFontArrayString = new String[]{};
    private ArrayAdapter<String> mArrayAdapter;
    private EditText etCustomName;
    private TextView tvReceiveable;
    private TextView tvFavoueable;
    private EditText etGetMoney;

    private List<EditInfoBean.CustomerListBean> customer_list = new ArrayList<>();
    private String ids = "";
    private Map<Integer, String> totalMoney = new HashMap<Integer, String>();
    String totalMoneyStr = "0";
    private String customer_name = "";
    private String[] idArray = new String[]{};
    private String[] numArray = new String[]{};
    private String[] priceArray = new String[]{};
    private String cache_data = "";//子页填写的菜品数据JSON格式
    private boolean isPurchase = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editinfo);

        ids = getIntent().getStringExtra("ids");
        isPurchase = getIntent().getBooleanExtra("isPurchase", false);
        initView();

    }

    private void initView() {
        View view = findViewById(R.id.titleBar);
        toolbarLeft = (ImageView) view.findViewById(R.id.toolbar_leftLin);
        toolbarTitle = (TextView) view.findViewById(R.id.toolbar_title);
        listOrderEdit = (ListView) findViewById(R.id.list_order_edit);
        toolbarTitle.setTextColor(getResources().getColor(R.color.blue));
        toolbarTitle.setText("营业信息编辑");
        btnClearAll = (TextView) findViewById(R.id.btn_clear_all);
        btnAdd = (TextView) findViewById(R.id.btn_add);
        btnCancle = (TextView) findViewById(R.id.btn_cancle);
        btnConfirm = (TextView) findViewById(R.id.btn_confirm);
        View footerView = LayoutInflater.from(this).inflate(R.layout.footer_edit_business_info, null);
        View headerView = LayoutInflater.from(this).inflate(R.layout.header_edit_bisiness_info, null);
        listOrderEdit.addFooterView(footerView);
        listOrderEdit.addHeaderView(headerView);

        initData();
        adapter = new EditInfoAdapter(getBaseContext(), mList);
        listOrderEdit.setAdapter(adapter);

        initFooterView(footerView);
        initListener();

    }

    private void initData() {
        HttpIndex.getIndexOrderCommit(getBaseContext(), ids, cache_data, isPurchase, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                cache_data = str;
                EditInfoBean editInfoBean = JSON.parseObject(str, new TypeReference<EditInfoBean>() {
                });
                List<EditInfoBean.CustomerListBean> customer_list = editInfoBean.getCustomer_list();

                idArray = new String[editInfoBean.getDishes_list().size()];
                numArray = new String[editInfoBean.getDishes_list().size()];
                priceArray = new String[editInfoBean.getDishes_list().size()];

                List<String> keyList = new ArrayList<String>();
                if (editInfoBean.getDishes_list() != null) {
                    for (Map.Entry<String, DishesInfoBean> dishes_list : editInfoBean.getDishes_list().entrySet()) {
                        DishesInfoBean dishesInfoBean = dishes_list.getValue();
                        mList.add(dishesInfoBean);
                        keyList.add(dishes_list.getKey());
                    }
                    for (int i = 0; i < keyList.size(); i++) {
                        idArray[i] = keyList.get(i);
                    }
                }
                //        初始化spinner中显示的数据
                if (customer_list != null) {
                    mFontArrayString = new String[customer_list.size() + 1];
                    for (int i = 0; i < customer_list.size(); i++) {
                        mFontArrayString[i] = customer_list.get(i).getCustomer_name();
                    }
                    mFontArrayString[customer_list.size()] = "自定义";
                }

                tvReceiveable.setText(editInfoBean.getTotal_price());

            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        }, null);
    }


    private void initListener() {
        toolbarLeft.setOnClickListener(this);
        btnClearAll.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        btnCancle.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        toolbarTitle.setOnClickListener(this);


        adapter.setOnItemClickListener(new EditInfoAdapter.OnEditListener() {
            @Override
            public void onEdit(String num, String price, int position) {
                Log.d("EditInfoActivity", num + "---" + price + "---" + position);
                totalMoney.put(position, ArithmeticUtils.mul(num, price, 2));//每一条的总额
                totalMoneyStr = "0";
                for (Map.Entry<Integer, String> totalMoneyMap : totalMoney.entrySet()) {
                    totalMoneyStr = ArithmeticUtils.add(totalMoneyStr, totalMoneyMap.getValue().toString());
                }
                etGetMoney.setText(totalMoneyStr);
                tvReceiveable.setText(totalMoneyStr);
                numArray[position] = num;
                priceArray[position] = price;
            }

            @Override
            public void onDelete(View view, int position) {
                mList.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
        etGetMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String favourable = "0";
                if (!TextUtils.isEmpty(s.toString())) {
                    favourable = s.toString();
                }
                tvFavoueable.setText(ArithmeticUtils.sub(totalMoneyStr, favourable, 2));
            }
        });
        etGetMoney.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                etGetMoney.setSelectAllOnFocus(true);
            }
        });

    }

    private void initFooterView(View footerView) {
        selectCustomSpinner = (Spinner) footerView.findViewById(R.id.spinner_select_custom);
        etCustomName = (EditText) footerView.findViewById(R.id.et_custom_name);
        tvReceiveable = (TextView) footerView.findViewById(R.id.tv_receivable);
        tvFavoueable = (TextView) footerView.findViewById(R.id.tv_favourable);
        etGetMoney = (EditText) footerView.findViewById(R.id.et_get_money);


        //        seeting_spinner改变了spinner的默认样式
        mArrayAdapter = new ArrayAdapter<String>(this, R.layout.edit_spinner, mFontArrayString) {
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
//                    设置spinner展开的Item布局
                    convertView = getLayoutInflater().inflate(R.layout.edit_spinner_item, parent, false);
                }
                TextView spinnerText = (TextView) convertView.findViewById(R.id.spinner_textView);
                spinnerText.setText(getItem(position));
                return convertView;
            }
        };
        selectCustomSpinner.setAdapter(mArrayAdapter);
//        spinner设置监听
        selectCustomSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                customer_name = mFontArrayString[position];
                if (position == mFontArrayString.length - 1) {
                    selectCustomSpinner.setVisibility(View.GONE);
                    etCustomName.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_leftLin:
                finish();
                break;
            case R.id.btn_cancle:
                finish();
                break;
            case R.id.btn_clear_all:
                mList.clear();
                adapter.notifyDataSetChanged();
                tvReceiveable.setText("");
                tvFavoueable.setText("");
                etGetMoney.setText("");
                break;
            case R.id.btn_add:
                startActivity(new Intent(this, NewBusinessInfoActivity.class));
                break;
            case R.id.btn_confirm:
                String getMoney = "0";
                if (!TextUtils.isEmpty(etGetMoney.getText().toString())) {
                    getMoney = etGetMoney.getText().toString();
                }
                if (etCustomName.getVisibility() == View.VISIBLE) {
                    customer_name = etCustomName.getText().toString();
                }
                HttpIndex.getOrderCreate(getBaseContext(), customer_name,
                        getMoney,
                        idArray,
                        numArray,
                        priceArray,isPurchase,
                        new OnResultListener() {
                            @Override
                            public void onSuccess(int requestCode, String str) {
                                startActivity(new Intent(EditInfoActivity.this, PrintDetailActivity.class)
                                        .putExtra("id", str)
                                        .putExtra("isPurchase",isPurchase));
                            }

                            @Override
                            public void onFailure(int requestCode, String str) {

                            }
                        }, null);


                break;
            case R.id.toolbar_title:
                startActivity(new Intent(this, IndexActivity.class));
                break;

        }
    }
}
